package com.travel.server.manager.impl.dal;

import com.travel.common.exception.WorkCode;
import com.travel.common.exception.WorkException;
import com.travel.server.manager.dao.DepartmentInfoDao;
import com.travel.server.manager.model.DepartmentInfo;
import com.travel.server.manager.model.DepartmentInfoExample;
import com.travel.server.manager.model.DepartmentMenu;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author: LiZhenhui
 * @Date: 2018/11/20 12:49
 * @Desc:
 */
@Component
@Slf4j
public class DepartmentDal {

    @Autowired
    private DepartmentInfoDao dao;

    public DepartmentInfo selectById(Integer id){
        DepartmentInfo departmentInfo = dao.selectByPrimaryKey(id);
        if(departmentInfo == null){
            log.info("未查询到部门信息，id{}", id);
            throw new WorkException(WorkCode.RECORD_NOT_EXIST);
        }
        return departmentInfo;
    }

    public PageDto<DepartmentInfo> select(DepartmentParam param){
        DepartmentInfoExample example = makeExample(param);
        int total = dao.countByExample(example);
        example.setOrderByClause("update_time desc");
        List<DepartmentInfo> list = dao.selectByExample(example);

        PageDto<DepartmentInfo> pageDto = new PageDto<>(list, total);
        return pageDto;
    }

    public List<DepartmentInfo> selectByExample(DepartmentParam param){
        if(param == null){
            param = new DepartmentParam();
        }
        DepartmentInfoExample example = makeExample(param);
        return dao.selectByExample(example);
    }

    public void insertOrUpdate(DepartmentInfo departmentInfo){
        if(departmentInfo.getId() == null){
            dao.insert(departmentInfo);
        }else{
            dao.updateByPrimaryKey(departmentInfo);
        }
    }

    private DepartmentInfoExample makeExample(DepartmentParam param){
        DepartmentInfoExample example = new DepartmentInfoExample();
        DepartmentInfoExample.Criteria criteria = example.or();
        if(param.getState() != null){
            criteria.andStateEqualTo(param.getState());
        }
        if(StringUtils.isNotBlank(param.getName())){
            criteria.andDepartmentNameEqualTo(param.getName());
        }
        if(param.getLimit() != null && param.getOffset() != null){
            example.setLimit(param.getLimit());
            example.setOffset(param.getOffset());
        }
        return example;
    }

    @Data
    public static class DepartmentParam{

        private Integer state = 1;

        private Integer limit;

        private Integer offset;

        private String name;
    }
}
